<?php
include('../fns_all.php');

function get_all_articles_ordered_by_date($offset, $rowsPerPage){
	$cxn = db_connect();
	$query = " SELECT * FROM articles order by date desc " .
	" LIMIT $offset, $rowsPerPage";
	$result = mysqli_query($cxn, $query) or die('Error, get_all_articles_ordered_by_date failed');
	return $result;
}

function get_numrows_of_articles(){
	$cxn = db_connect();
	$query   = "SELECT COUNT(id) AS numrows FROM articles";
	$result  = mysqli_query($cxn, $query) or die('Error, get_numrows_of_articles failed');
	$row     = mysqli_fetch_assoc($result);
	return $row['numrows'];
}

function get_article_by_id($id){
	$cxn = db_connect();
	$result = mysqli_query($cxn, "SELECT * FROM articles WHERE id='$id'");
	$result = mysqli_fetch_assoc($result);
	return $result;
}

function vote_for_article($rating, $id){
	$cxn = db_connect();
	mysqli_query($cxn, "update articles set votes=votes + 1, total_rating=total_rating+'$rating' WHERE id='$id'");
}

function insert_comment_for_article($comment, $author, $id){
	$cxn = db_connect();
	$result = mysqli_query ($cxn, "INSERT INTO articles_comments (text, author, article_id) VALUES ('$comment', '$author','$id')");
	return $result;
}

function get_all_comments_for_article($id){
	$cxn = db_connect();
	$result = mysqli_query($cxn, "SELECT * FROM articles_comments where article_id='$id' order by date desc");
	return $result;
}

function insert_article($title, $description, $text, $author, $imagename){
	$cxn = db_connect();
	$result = mysqli_query ($cxn, "INSERT INTO articles (title,description,text,author, img_path) VALUES ('$title','$description','$text','$author', '$imagename')");
	return $result;
}

function update_article_with_imagename($title, $description, $text, $author, $imagename, $id){
	$cxn = db_connect();
	$query = "UPDATE articles SET title='$title', description='$description', text='$text', author='$author', img_path='$imagename' WHERE id='$id'";
	return mysqli_query( $cxn, $query);
}

function update_article_without_imagename($title, $description, $text, $author, $id){
	$cxn = db_connect();
	return mysqli_query( $cxn, "UPDATE articles SET title='$title', description='$description', text='$text', author='$author' WHERE id='$id'");
}

function delete_article($id){
	$cxn = db_connect();
	return mysqli_query ($cxn, "DELETE FROM articles WHERE id='$id'");
}

?>